package com.sly.fuxi;

import java.io.FileInputStream;

/**
 * @author SLY
 * {@code @date} 2025/2/3
 */
public class MyClassLoadTest {
    static class MyClassLoader extends ClassLoader {
        private final String classPath;

        public MyClassLoader(String classPath) {
            this.classPath = classPath;
        }


        @Override
        protected Class<?> findClass(String name) throws ClassNotFoundException {
            byte[] data = new byte[0];
            try {
                data = loadClassData(name);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return defineClass(name, data, 0, data.length);
        }

        @Override
        protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
            Class<?> clazz = findLoadedClass(name);
            if (clazz == null) {
                // 打破双亲委派机制
                if (!name.startsWith("com.sly.fuxi")) {
                    clazz = getParent().loadClass(name);
                } else {
                    clazz = findClass(name);

                }

            }
            if (resolve) {
                resolveClass(clazz);
            }
            return clazz;
        }

        private byte[] loadClassData(String name) throws Exception {
            name = name.replaceAll("\\.", "/");
            FileInputStream fis = new FileInputStream(classPath + "/" + name
                    + ".class");
            int len = fis.available();
            byte[] data = new byte[len];
            fis.read(data);
            fis.close();
            return data;
        }


    }


    public static void main(String[] args) throws Exception {
        MyClassLoader loader = new MyClassLoader("D:\\Test\\classLoader");

        Class<?> clazz = loader.loadClass("com.sly.fuxi.MyClass01");
        Object obj = clazz.newInstance();
        clazz.getDeclaredMethod("out").invoke(obj);
        System.out.println(obj.getClass().getClassLoader());

    }
}
